package ar.com.blacktobacco;

import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutionException;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;

public class Practico12Activity extends Activity {
	/** Called when the activity is first created. */

	public static final String NEWS_FEED = "https://news.google.com/news/feeds?ned=us&topic=w&output=rss";

	private RSSChannel channel;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// TODO: display progress

		ParseFeedAsyncTask parseFeedAT = new ParseFeedAsyncTask();
		try {
			parseFeedAT.execute(new URL[] { new URL(NEWS_FEED) });
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

		try {
			channel = parseFeedAT.get();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		RSSChannelAdapter adapter = new RSSChannelAdapter(this, R.layout.item,
				channel.getItem());

		ListView lv = (ListView) findViewById(R.id.listView1);

		TextView channelTitle = (TextView) findViewById(R.id.channelTitle);
		channelTitle.setText(channel.getTitle());

		lv.setAdapter(adapter);

	}

	private class ParseFeedAsyncTask extends
			AsyncTask<URL, Integer, RSSChannel> {

		@Override
		protected RSSChannel doInBackground(URL... params) {
			URL urlToParse = params[0];
			RSSParserHandler handler = null;
			SAXParserFactory factory = SAXParserFactory.newInstance();
			try {
				SAXParser parser = factory.newSAXParser();
				handler = new RSSParserHandler();
				parser.parse((InputStream) urlToParse.getContent(), handler);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}

			return handler.getChannel();
		}

		@Override
		protected void onPostExecute(RSSChannel result) {
			super.onPostExecute(result);

		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

	}
}